﻿

Function Invoke-WebRequestLessV3
{
        [cmdletbinding()]
        Param( 
        [String] 
        $Uri,

        [Parameter(Mandatory=$false)] 
        [PSCredential]
        $Credential

        )

    Begin
    {
        $watch = [system.diagnostics.stopwatch]::StartNew() 
        write-verbose "Start Invoke-WebRequestLessV3 for $Uri"
    }
    End
    {
        write-verbose "End Invoke-WebRequestLessV3 for $Uri"
        $watch.Stop();
        Write-Verbose "function duration : $($watch.Elapsed)"
    }

    process
    {
        
        $requestResponse = New-Object PSObject -Property @{
                    Uri=$Uri
                    StatusCode=-1
                    HttpResponseCode=""
                    HttpResponse=""
                    Content =""
                    }

                       
        $req = [system.Net.WebRequest]::Create($Uri)

        if ($Credential)
        {
            $req.Credentials = $Credential.GetNetworkCredential()
        }


        try 
        {
            $res = $req.GetResponse()
            [IO.Stream] $stream = $res.GetResponseStream()
            [IO.StreamReader] $reader = New-Object IO.StreamReader($stream)
            [string] $output = $reader.readToEnd()
            $stream.flush()
            $stream.close()

        } 
        catch [System.Net.WebException] 
        {
            $res = $_.Exception.Response
        }
        finally
        {
            if ($stream)
            {
                $stream.Close()
                $stream.Dispose()
            }

            $requestResponse.StatusCode = [int]$res.StatusCode
            $requestResponse.HttpResponseCode = $res.StatusCode
            $requestResponse.HttpResponse = $res
            $requestResponse.Content = $output
            

        }

        Write-Output $requestResponse
    }
}

function ConvertTo-Base64($string) {
   $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
   $encoded = [System.Convert]::ToBase64String($bytes); 


   return $encoded;
}


function ConvertFrom-Base64($string) {
   $bytes  = [System.Convert]::FromBase64String($string);
   $decoded = [System.Text.Encoding]::UTF8.GetString($bytes); 


   return $decoded;
}

